"use client";
import React, {createContext, useContext, useState} from "react";
import {RecordProps} from "./interface";

// 初始化
interface ContextProps {
  PAGE_SIZES: number[];

  page: number;
  pageSize: number;
  fetching: boolean;
  records: RecordProps[];
  selectedRecords: RecordProps[];
  totalRecords: number;

  setPage: (page: number) => void;
  setPageSize: (size: number) => void;
  setFetching: (fetching: boolean) => void;
  setRecords: (records: RecordProps[]) => void;
  setSelectedRecords: (records: RecordProps[]) => void;
  setTotalRecords: (totalRecords: number) => void;
}

// 创建Context
const IpdTableContext = createContext<ContextProps | null>(null);

// 导出Context组件
export function IpdTableProvider({children}: {children: React.ReactNode}) {
  const PAGE_SIZES = [5, 10, 15];

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[1]);
  const [fetching, setFetching] = useState(false);
  const [records, setRecords] = useState<RecordProps[]>([]);
  const [selectedRecords, setSelectedRecords] = useState<RecordProps[]>([]);
  const [totalRecords, setTotalRecords] = useState(0);
  return (
    <IpdTableContext.Provider
      value={{
        PAGE_SIZES,
        page,
        pageSize,
        fetching,
        records,
        selectedRecords,
        totalRecords,
        setPage,
        setPageSize,
        setFetching,
        setRecords,
        setSelectedRecords,
        setTotalRecords,
      }}
    >
      {children}
    </IpdTableContext.Provider>
  );
}

// 导出钩子函数
export const useIpdTableContext = () => {
  const context = useContext(IpdTableContext);
  if (context === null) {
    throw new Error("useIpdTableContext不存在");
  }
  return context; // 返回context
};
